import Vue from 'vue'
import Router from 'vue-router'
import store from '@/store'
import api from '@/http/api'
import routesAM from "./modules/routesAM"
import routesPW from "./modules/routesPW"
import routesBL from "./modules/routesBL"
import routesYB from "./modules/routesYB"
import {
    isDev,
    devMember
} from "../config/devConfig";
import Cookies from 'js-cookie'
import wx from 'weixin-js-sdk'
import {
    getUrlParamObj,
    isNullJSON
} from '@/utils/tools'
import {
    Dialog
} from 'vant';

Vue.use(Router)
Vue.use(Dialog);


console.log("router isDev ", isDev)
/** 配置需用JSAPI的路由 */
const jsApiRouters = ['/share', '/take_photo', '/traffic', '/congratulationl']

/** 白名单路由 - - 没绑定手机号码可访问视图资讯类页面：演艺活动、商场活动、交通指南、商家*/
const whiteFilterRoutes = store.state.app.whiteRoutes

//黑名单路由 -- 用于非注册前弹窗提示  推荐有礼 转盘 停车缴费 积分商城 抢优惠券
const blackRouters = store.state.app.blackRouters


let routes = [{
        path: '/',
        name: '首页',
        component: () => import('@/views/Home'),
        meta: {
            title: '国际体育文化演艺中心',
            tabsIndex: 0,
        }

    },
    {
        path: '/author',
        name: '授权页',
        component: () => import('@/views/Author'),
        meta: {
            title: '正在登录...',
            tabsIndex: 0,
        }
    }
]
routes = routes.concat(routesAM)
routes = routes.concat(routesPW)
routes = routes.concat(routesBL)
routes = routes.concat(routesYB)

const router = new Router({
    routes
})

router.beforeEach((to, from, next) => {

    document.title = to.meta.title || '国际文化体育演艺中心'
    // alert('to.fullPath '+to.fullPath)
    isDev && console.log(to.fullPath)

    var urlVals = getUrlParamObj();

    // console.log("urlVals ",urlVals)
    if (urlVals && urlVals.share_mobile) {
        Cookies.set("share_mobile", urlVals.share_mobile, {
            expires: 1
        })
        window.location.href = '/index.html' //分享标记 获取分享人标记,跳转一次首页
    }

    let userInfoExisteTime = Cookies.get("userInfoExisteTime") || false;
    if (!userInfoExisteTime) {
        let interVal = 5;
        console.log("每%d分钟更新一次userInfo", interVal)
        store.dispatch("fetchUserInfo")
        Cookies.set('userInfoExisteTime', true, {
            expires: new Date(new Date().getTime() + interVal * 60 * 1000)
        });
    }

    let token = Cookies.get("token")
    let userInfo = store.state.user.userInfo

    /** 开发模式 */
    if (isDev) {
        let new_userInfo = {}
        let new_token = ''
        let new_mobile = ''
        if (devMember === 'WU') {
            new_token = 'ofeKL1G5CwBcWtlW9g49uWoStxY8'
            new_userInfo = {
                openId: new_token,
                nickname: '麦克·普洱茶',
                mobile: '',
                sexDesc: '男',
                sex: '1',
                language: 'zh_CN',
                city: '佛山',
                province: '广东',
                country: '',
                privileges: [],
                headImgUrl: 'http://thirdwx.qlogo.cn/mmopen/vi_32/q7kOWzzfk4DJSH3QgtBH7pLhXz73eBvXWKgG13HHhXJnB81fWxic0KTwEoZOo4WlLXiciaFkcUDc1ibCTfYbpiaWJUw/132'
            }
            new_token = 'ofeKL1G5CwBcWtlW9g49uWoStxY8'
            new_mobile = '15920483330'
        } else if (devMember === 'MA') {
            new_token = 'oxAtC1rk5vuESt3HHuhOEoH_R8eQ'
            new_userInfo = {
                openId: new_token,
                nickname: '浩...东',
                mobile: '',
                sexDesc: '男',
                sex: '1',
                language: 'zh_CN',
                city: '佛山',
                province: '广东',
                country: '',
                privileges: [],
                headImgUrl: 'http://thirdwx.qlogo.cn/mmopen/ib1erEEC8Z8LbmiawLiaFSJM5WicoQXIBoWldwiajm9rQHhaLW09zAZERLo25d0XFX7uhmCy82L8vG1mOHHAhG9hOIxicmZicxG5ecY/132'
            }
            new_mobile = '13318269535'
        } else if (devMember === 'YB') {
            new_token = 'oseFkty8lg65UQuKh-scfLY0ry3s'
            new_userInfo = {
                openId: new_token,
                nickname: '11111',
                mobile: '',
                sexDesc: '男',
                sex: '1',
                language: 'zh_CN',
                city: '佛山',
                province: '广东',
                country: '',
                privileges: [],
                headImgUrl: 'http://thirdwx.qlogo.cn/mmopen/5BnwCXMvvxIFuj9z6NOoVjlqc8uHKXeYudDAJ3ov0KyxMicViaHDy6wpiaLEW2vhwApC4HpsHxICiaXGPwUhHCwLLPuyIpYgodNg/132'
            }
            new_mobile = '13690760401'
        } else if (devMember === 'TEST') {
            new_token = 'oseFktyycTtWBQoyuPOkuNdR6IwI'
            new_userInfo = {
                openId: new_token,
                nickname: '友诚IT',
                mobile: '',
                sexDesc: '男',
                sex: '1',
                language: 'zh_CN',
                city: '佛山',
                province: '广东',
                country: '',
                privileges: [],
                headImgUrl: 'http://thirdwx.qlogo.cn/mmopen/1gvL9ficRs1H6AQ5L4WAvdvf9kLdqXvia0EicE6ByqDP3Jl3IHne1IZTdSHiblqxDIsBtWHQVjQvGOjvffiaQTlHZkBesmC70ubAx/132'
            }
            new_mobile = '15920482043'
        } else {
            new_token = 'oiQAFuA5sUC18iViiZmaHU8FK9-8'
            new_userInfo = {
                openId: new_token,
                nickname: '麦克·普洱茶',
                mobile: '',
                sexDesc: '男',
                sex: '1',
                language: 'zh_CN',
                city: '佛山',
                province: '广东',
                country: '',
                privileges: [],
                headImgUrl: 'http://thirdwx.qlogo.cn/mmopen/vi_32/q7kOWzzfk4DJSH3QgtBH7pLhXz73eBvXWKgG13HHhXJnB81fWxic0KTwEoZOo4WlLXiciaFkcUDc1ibCTfYbpiaWJUw/132'
            }
            new_mobile = '15920483330'
        }
        if (!token) { //模拟数据
            Cookies.set("token", new_token, {
                expires: 1
            })
        }
        if (!new_userInfo.mobile) {
            new_userInfo.mobile = new_mobile
        }
        if (!userInfo || !userInfo.length || userInfo.length <= 0) {
            console.log("[模拟数据]new_userInfo ", new_userInfo);
            store.commit("setUserInfo", new_userInfo)
            userInfo = store.state.user.userInfo
        }
        console.log("[开发模式]userInfo ", userInfo)
    }
    if (token && !userInfo.mobile) {
        // let flag = whiteFilterRoutes.some(val => val == to.path)
        // isDev && console.log("flag ", flag)
        // if (!flag) {
        //     next('/register');
        //     return false
        // }

        let flag = blackRouters.some(item => {
            return item == to.path
        })
        if (flag && !userInfo.mobile) {
            Dialog.confirm({
                title: '温馨提示',
                message: '请先绑定手机号码，再访问本栏目内容，谢谢！'
            }).then(() => {
                // store.state.app.toUrl = to.path
                store.commit("SET_URL",to.path)
                next('/register')
            }).catch(() => {
                // on cancel
                next(false)
            });
            return false
        }


    }

    if (!isDev) {
        if (to.path === '/author' && token) {
            if(userInfo&&!userInfo.mobile){
                next('/register');
                return false
            }
            next('/');
            return false
        }
        if (!token && to.path === '/register') {
            // console.log(to.fullPath)
            store.commit("SET_URL",to.path)
            next('/author');
            return false
        }
        if (!token && to.path !== '/author') {
            console.log(to.fullPath)
            // store.state.app.toUrl = to.fullPath;
            store.commit("SET_URL",to.fullPath)
            next('/author');
            return false
        }
        if (token) {

            next();
            return false
        }
    }
    next();
})



function getJsApiConfig() {
    let url = window.location.href.split('#')[0];
    api.app.jsApiConfig({
        "url": url
    }).then(res => {
        let data = res.data
        wx.config({
            debug: false,
            appId: data.appId,
            timestamp: data.timestamp,
            nonceStr: data.nonceStr,
            signature: data.signature,
            jsApiList: [
                'checkJsApi',
                'chooseImage',
                'previewImage',
                'uploadImage',
                'downloadImage',
                'getLocalImgData',
                'scanQRCode',
                'chooseWXPay',
                'openLocation',
                'getLocation',
                'updateAppMessageShareData',
                'updateTimelineShareData',
            ]
        })
    })
}


router.afterEach((to, from) => {
    document.body.scrollTop = 0;
    document.documentElement.scrollTop = 0;
    if (!isDev) {
        let flag = jsApiRouters.some((val) => {
            return val === to.path
        })
        if (flag) getJsApiConfig()
    }
})

export default router
